package com.itany.websocket.websocket.websocket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TalkWebSocketHandler extends TextWebSocketHandler {

    public static Map<String,WebSocketSession> users=new ConcurrentHashMap<>();

    //连接成功时调用
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接成功------------------------");
        
        String nickname= (String) session.getAttributes().get("nickname");

        System.out.println("nickname = " + nickname);

        users.put(nickname,session);
    }

    //相当于HttpServlet的service方法
    //客户端请求到达时调用
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("接收客户端请求------------------------");
        String nickname= (String) session.getAttributes().get("nickname");
        System.out.println("nickname = " + nickname);
        System.out.println("message = " + message.getPayload());

        for (Map.Entry<String,WebSocketSession> userEntry : users.entrySet()) {
            synchronized ("abc") {
                if(session.isOpen()&&userEntry.getValue().isOpen()){
                    //服务器向客户端推送消息
                    userEntry.getValue().sendMessage(new TextMessage(nickname+":"+message.getPayload()+" "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                }
            }
        }

    }

    //连接异常时调用
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常------------------------");
    }

    //连接关闭时调用
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭------------------------");
    }
}
